<?php

namespace app\admin\controller\uniwigs;

use app\common\controller\Backend;
use think\Db;
/**
 * 规则管理
 *
 * @icon fa fa-circle-o
 */
class Membercharge extends Backend
{
    
    /**
     * CashCodeRule模型对象
     * @var \app\admin\model\Membercharge
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Membercharge');
		
		
		$form_params =  [
			
			[	
				'zone'=>'add,edit',
				'key'=> 'amount',
				'name'=> '金额',
				'form' => 'input',
				'form_type' => 'text',
				'required'=>true
				
			],
			[	
				'zone'=>'edit',
				'key'=> 'pre_amount',
				'name'=> '充值前金额',
				'form' => 'input',
				'form_type' => 'text',
				'required'=>false
				
			],
			[	
				'zone'=>'edit',
				'key'=> 'now_amount',
				'name'=> '充值后金额',
				'form' => 'input',
				'form_type' => 'text',
				'required'=>false
				
			],
			
			
			[	
				'zone'=>'add,edit',
				'key'=> 'iphone',
				'name'=> '手机号',
				'form' => 'input',
				'form_type' => 'text',
				'required'=>true
				
			],
			
			[	
				'zone'=>'add,edit',
				'key'=> 'username',
				'name'=> '客户姓名',
				'form' => 'input',
				'form_type' => 'text'	,
				'required'=>false
			],
			
			[	
				'zone'=>'add,edit',
				'key'=> 'note',
				'name'=> '备注',
				'form' => 'input',
				'form_type' => 'text',
				'required'=>true				
			]
			
			
		];
		
		$this->view->assign("form_params", $form_params);

    }
    
     /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {	
	
			
			
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
		
			
			//每个不同model 的 主键 不一致 默认为id 所以这里搜索要指定为 此model 的主键 id_code 
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('id');

			
            $total = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->count();
			
			
		
			
            $list = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
		
			

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
	
	
	 /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
			
            if ($params)
            {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill)
                {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try
                {	
				
					
					$params['amount'] = number_format( abs($params['amount'] ),2, '.', '');
					if(isset($params["'action'"])){
						
						$params['action'] =  '-';
						
						$params['amount'] =  0  -  $params['amount'];
					}else{
						
						$params['action'] =  '+';
					}
				
				
					//检测手机号 是否存在 对应的客户  
					$getCustomer_info = Db::name('member')->where('iphone', '=', $params['iphone'])->select();
					$amount = trim($params['amount']);
					$iphone = trim($params['iphone']);
				
					
					
					if($getCustomer_info){
						//客户存在  
						$customer = $getCustomer_info[0];
						
						$preamount =   number_format($customer['balance'] ,2, '.', '');
						$params['preamount'] =  $preamount;
						
						$customer_banlance = $preamount   +  number_format( $params['amount']  ,2, '.', '');
						
						
						$params['now_amount'] =  $customer_banlance;
					
						
						if($params['now_amount']  < 0 ){
							
							$this->error('手机号['.$iphone . ']姓名[' +$params['username']  +']当前客户所用余额不足，当前余额[],消费金额[]，请修改消费金额!!!');
							
						}
						
						
					}else{
						//报错 要新建客户 才能充值 
						
						 $this->error('手机号'.$iphone . '对应的客户不存在，请先建立会员信息，再进行充值');
					}
					
				
					
					$user = $this->auth->getUserInfo();
					$params['username'] =  $customer['username'] ;
					$params['actor'] =  $user['username'] ;
					
					
				
					
                    //是否采用模型验证
                    if ($this->modelValidate)
                    {	
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
					
					//检测 
					$result = $this->model->allowField(true)->save($params);
                    
                    if ($result !== false)
                    {	
				
						//增加 客户balance余额 
						 Db::execute("update fa_member  set  balance = ".  $customer_banlance ." where id=  " .$customer['id']);
				
				
                        $this->success();
                    }
                    else
                    {
                        $this->error($this->model->getError());
                    }
                }
                catch (\think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

}
